/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package TwatClasses;

import Entities.Messages;
import Entities.Messages_;
import Entities.Reply;
import Entities.Reply_;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

/**
 *
 * @author xespin
 */
public class MessageReply{
    @PersistenceContext
    private EntityManager m_entityManager;
    
    public MessageReply(){
       
    }
    
    /**
     * Send a list of replies for a given message
     * @param receiverId
     * @param messageId
     * @return 
     */
    public List<Messages> getReplies(Long receiverId, Long messageId){
        
        List<Messages> messList = null;
        Comparator<Messages> messageComparator = new MessageComparator();
        //recuperation des mreponses par ID
        CriteriaBuilder cBuilder = m_entityManager.getCriteriaBuilder();
        
        CriteriaQuery<Reply> queryReply = cBuilder.createQuery(Reply.class);
        Root<Reply> rootReply = queryReply.from(Reply.class);
        queryReply.where(cBuilder.and(cBuilder.equal(rootReply.get(Reply_.receiveridfk),receiverId),
                cBuilder.equal(rootReply.get(Reply_.messageidfk), messageId)));
        queryReply.select(rootReply);
        
        try{
            List<Reply> messReply = m_entityManager.createQuery(queryReply).getResultList();
            
            HashSet<Long> replyIds = new HashSet<Long>();
            for(Reply repId: messReply){
                replyIds.add(repId.getMessageidfk());
            }
            
            CriteriaQuery<Messages> queryMess = cBuilder.createQuery(Messages.class);
            Root<Messages> rootMessages = queryReply.from(Messages.class);
            queryMess.where(rootMessages.get(Messages_.id).in(replyIds));
            queryMess.select(rootMessages);
           
            try{
                messList = m_entityManager.createQuery(queryMess).getResultList();
                Collections.sort(messList,messageComparator);
                return messList;
            }catch(NoResultException  ex){
                return null;
            }
        }catch(NoResultException  ex){
            return null;
        }
    }
}
